package org.example.controller;

import org.example.dao.OrderItemMapper;
import org.example.dao.OrderMapper;
import org.example.dao.TableInfoDao;
import org.example.dish_pojo.Order;
import org.example.dish_pojo.OrderCreateRequest;
import org.example.dish_pojo.OrderItem;
import org.example.enum_pojo.OrderStatus;
import org.example.pojo.TableInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/orderFood")
public class OrderFoodController {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private TableInfoDao tableInfoMapper;

    /**
     * 创建订单（包含主单和明细）
     */
    @PostMapping("/createOrder")
    public Map<String, Object> createOrder(@RequestBody OrderCreateRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 1. 插入订单主表
            Order order = new Order();
            order.setOrderNo(request.getOrderNo());
            order.setUserId(request.getUserId());
            order.setTableId(request.getTableId());
            order.setOrderType(request.getOrderType());
            order.setStatus(OrderStatus.PENDING_PAY);
            order.setCreateTime(new Date());
            order.setTotalAmount(BigDecimal.valueOf(request.getTotalAmount()));
            order.setPayMethod(request.getPayMethod());
            order.setNotes(request.getNotes());

            orderMapper.insert(order);

            // 2. 插入订单明细
            for (OrderItem item : request.getItems()) {
                item.setOrderId(order.getOrderId());
                orderItemMapper.insert(item);
            }

            // 3. 更新桌位状态为占用
            if (request.getTableId() != null) {
                TableInfo table = tableInfoMapper.selectById(request.getTableId());
                if (table != null && "idle".equals(table.getStatus())) {
                    table.setStatus("occupied");
                    table.setOccupyTime(new Date());
                    tableInfoMapper.updateById(table);
                }
            }

            result.put("code", 200);
            result.put("msg", "订单创建成功");
            result.put("data", Map.of("orderId", order.getOrderId(), "orderNo", order.getOrderNo()));

        } catch (Exception e) {
            result.put("code", 500);
            result.put("msg", "订单创建失败：" + e.getMessage());
        }

        return result;
    }

}
